import React, { useState } from 'react';
import {
  Modal,
  Form,
  Input,
  Select,
  Row,
  Col,
  message,
  DatePicker,
  Upload,
  Switch,
  Radio,
  Checkbox,
  InputNumber,
  Button,
} from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { MEMBER_FORM_CONFIG, MEMBER_EDIT_FORM_CONFIG, FIELD_TYPES, VALIDATION_RULES } from './formConfig';
import { useDictionary } from '../../hooks/useDictionary';
import { MEMBER_TYPE_DICT_TYPE, SKILL_TYPE_DICT_TYPE } from './memberTypes';

const { Option } = Select;
const { TextArea } = Input;

// 通用表单字段渲染器
const FormFieldRenderer = ({ field, mode = 'add', form, allowPasswordEdit }) => {
  const { name, label, type, required, placeholder, options, span, rules = [], ...rest } = field;

  // 构建验证规则
  const baseRules = required ? [VALIDATION_RULES.required(`请输入${label}`)] : [];
  const fieldRules = [...baseRules, ...rules];

  // 定义编辑模式下不允许修改的字段
  const readOnlyFields = ['memberName', 'username'];
  const isReadOnly = mode === 'edit' && readOnlyFields.includes(name);

  // 密码字段特殊处理：在编辑模式下根据开关状态控制禁用
  const isPasswordField = name === 'password' && mode === 'edit';
  const isPasswordDisabled = isPasswordField && !allowPasswordEdit;

  // 通用属性
  const commonProps = {
    placeholder,
    disabled: isReadOnly || isPasswordDisabled,
    ...rest
  };

  // 根据字段类型渲染对应的组件
  const renderField = () => {
    switch (type) {
      case FIELD_TYPES.TEXT:
        return <Input {...commonProps} />;

      case FIELD_TYPES.PASSWORD:
        return <Input.Password {...commonProps} />;

      case FIELD_TYPES.TEXTAREA:
        return <TextArea {...commonProps} />;

      case FIELD_TYPES.SELECT:
        return (
          <Select {...commonProps}>
            {options?.map(option => (
              <Option key={option.value} value={option.value}>
                {option.label}
              </Option>
            ))}
          </Select>
        );

      case FIELD_TYPES.MULTI_SELECT:
        return (
          <Select mode="multiple" {...commonProps}>
            {options?.map(option => (
              <Option key={option.value} value={option.value}>
                {option.label}
              </Option>
            ))}
          </Select>
        );

      case FIELD_TYPES.RADIO:
        return (
          <Radio.Group {...commonProps}>
            {options?.map(option => (
              <Radio key={option.value} value={option.value}>
                {option.label}
              </Radio>
            ))}
          </Radio.Group>
        );

      case FIELD_TYPES.CHECKBOX:
        return (
          <Checkbox.Group {...commonProps}>
            {options?.map(option => (
              <Checkbox key={option.value} value={option.value}>
                {option.label}
              </Checkbox>
            ))}
          </Checkbox.Group>
        );

      case FIELD_TYPES.DATE:
        return <DatePicker {...commonProps} style={{ width: '100%' }} />;

      case FIELD_TYPES.NUMBER:
        return <InputNumber {...commonProps} style={{ width: '100%' }} />;

      case FIELD_TYPES.SWITCH:
        return <Switch {...commonProps} />;

      case FIELD_TYPES.UPLOAD:
        return (
          <Upload {...commonProps}>
            <Button icon={<UploadOutlined />}>点击上传</Button>
          </Upload>
        );

      default:
        return <Input {...commonProps} />;
    }
  };

  return (
    <Col span={span || 12} key={name}>
      <Form.Item
        label={label}
        name={name}
        rules={fieldRules}
        valuePropName={type === FIELD_TYPES.SWITCH ? 'checked' : undefined}
      >
        {renderField()}
      </Form.Item>
    </Col>
  );
};

// 表单分组渲染器
const FormGroupRenderer = ({ group, mode = 'add', form, allowPasswordEdit }) => {
  return (
    <div key={group.key} style={{ marginBottom: 24 }}>
      <h3 style={{
        marginBottom: 16,
        color: '#1890ff',
        borderBottom: '1px solid #f0f0f0',
        paddingBottom: 8
      }}>
        {group.title}
      </h3>
      <Row gutter={16}>
        {group.fields.map(field => (
          <FormFieldRenderer key={field.name} field={field} mode={mode} form={form} allowPasswordEdit={allowPasswordEdit} />
        ))}
      </Row>
    </div>
  );
};

  // 通用表单组件
const DynamicForm = ({ config, form, initialValues = {}, mode = 'add', allowPasswordEdit, onValuesChange }) => {
  return (
    <Form
      form={form}
      layout="vertical"
      preserve={false}
      initialValues={mode === 'add' ? {} : initialValues}
      onValuesChange={onValuesChange}
    >
      {config.groups.map(group => (
        <FormGroupRenderer key={group.key} group={group} mode={mode} form={form} allowPasswordEdit={allowPasswordEdit} />
      ))}
    </Form>
  );
};

// 成员表单组件
const AddMembers = ({
  visible,
  onCancel,
  onSuccess,
  initialValues = {},
  mode = 'add',
  config
}) => {
  // 根据模式选择不同的表单配置
  const formConfig = config || (mode === 'edit' ? MEMBER_EDIT_FORM_CONFIG : MEMBER_FORM_CONFIG);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [allowPasswordEdit, setAllowPasswordEdit] = useState(false);
  const { dictList: memberTypes } = useDictionary(MEMBER_TYPE_DICT_TYPE, true);
  const { dictList: skillTypes } = useDictionary(SKILL_TYPE_DICT_TYPE, true);

  // 动态创建表单配置，使用从字典获取的成员类型和技能类型
  const dynamicConfig = React.useMemo(() => {
    const updatedConfig = { ...formConfig };
    
    // 更新成员角色选项 - 优先使用字典数据，获取不到时使用默认值
    const basicGroup = updatedConfig.groups.find(group => group.key === 'basic');
    if (basicGroup) {
      const roleField = basicGroup.fields.find(field => field.name === 'memberType');
      if (roleField) {
        roleField.options = memberTypes.length > 0 ? memberTypes : roleField.options;
      }
    }
    
    // 更新技能选项 - 优先使用字典数据，获取不到时使用默认值
    const skillsGroup = updatedConfig.groups.find(group => group.key === 'skills');
    if (skillsGroup) {
      const skillsField = skillsGroup.fields.find(field => field.name === 'skills');
      if (skillsField) {
        skillsField.options = skillTypes.length > 0 ? skillTypes : skillsField.options;
      }
    }
    
    return updatedConfig;
  }, [config, memberTypes, skillTypes]);

  const handleOk = async () => {
    try {
      setLoading(true);
      const values = await form.validateFields();

      // 处理密码字段：在编辑模式下，如果不允许修改密码，则从提交数据中移除密码字段
      const submitData = { ...values };

      if (mode === 'edit' && !values.allowPasswordEdit) {
        delete submitData.password;
      }

      // 将技能数组转换为JSON字符串格式传递给后端
      const finalSubmitData = {
        ...submitData,
        // 如果skills是数组，转换为JSON字符串
        ...(submitData.skills && Array.isArray(submitData.skills) && {
          skills: JSON.stringify(submitData.skills)
        })
      };

      form.resetFields();
      onSuccess && onSuccess(finalSubmitData);
      onCancel();
    } catch (error) {
      console.error('表单验证失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    form.resetFields();
    onCancel();
  };

  // 监听editingMember变化，重置表单
  React.useEffect(() => {
    if (visible) {
      if (initialValues && mode === 'edit') {
        // 编辑模式：将JSON字符串格式的skills转换为数组格式供表单使用
        const processedValues = {
          ...initialValues,
          allowPasswordEdit: false, // 编辑模式下密码开关默认为关闭
          password: '', // 编辑模式下密码字段默认为空
          ...(initialValues.skills && {
            skills: typeof initialValues.skills === 'string'
              ? JSON.parse(initialValues.skills)
              : initialValues.skills
          })
        };
        form.setFieldsValue(processedValues);
        setAllowPasswordEdit(false);
      } else {
        form.resetFields();
        setAllowPasswordEdit(false);
      }
    }
  }, [visible, initialValues, form, mode]);

  return (
    <Modal
      title={`${mode === 'add' ? '添加' : '编辑'}${formConfig.title}`}
      visible={visible}
      onOk={handleOk}
      onCancel={handleCancel}
      width={900}
      confirmLoading={loading}
    >
      <DynamicForm
        config={dynamicConfig}
        form={form}
        initialValues={initialValues}
        mode={mode}
        allowPasswordEdit={allowPasswordEdit}
        onValuesChange={(changedValues) => {
          if (mode === 'edit' && 'allowPasswordEdit' in changedValues) {
            setAllowPasswordEdit(changedValues.allowPasswordEdit || false);
          }
        }}
      />
    </Modal>
  );
};

export default AddMembers;
